package com.ys.contl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;

@ControllerAdvice
public class ControllerExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    @Autowired
    private MailService mailService;

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<ErrorInfo> handlerRumtimeException(HttpServletRequest request, RuntimeException e){
        ErrorInfo errorInfo = new ErrorInfo();
        errorInfo.setResultCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        errorInfo.setMessage("服务器内部错误");
        errorInfo.setUrl(request.getRequestURL().toString());
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        LOGGER.info("\n"+request.getRequestURL().toString()+"--"+ sw.toString());
        mailService.sendSimpleMail("342827661@qq.com", "错误","您好，在"+request.getRequestURL().toString()+"请求上报错,错误详情如下：\n"+e.getMessage());
        pw.close();
        return new ResponseEntity<ErrorInfo>(errorInfo,HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
